﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using BlackXS.Info;

namespace PluginXtraZone
{
    public class WebRequester
    {
        public Int32 TimeOut { get; set; }

        //Webrequest
        HttpWebRequest req;
        HttpWebResponse res;

        CookieContainer cookieJar;

        public WebRequester()
        {
            //wird gebraucht damit man sich einloggen kann
            System.Net.ServicePointManager.Expect100Continue = false;
            cookieJar = new CookieContainer();
        }

        //GetRequest Methode
        public string GetRequest(string url, string refferer)
        {
            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.CookieContainer = cookieJar;
                req.Method = "GET";
                req.KeepAlive = true;
                req.Referer = refferer;
                req.Timeout = TimeOut;
                req.UserAgent = ("User-Agent: " + AssemblyInfo.AssemblyTitle + "/" + AssemblyInfo.AssemblyVersion);
                req.ContentType = "application/x-www-form-urlencoded";
                res = (HttpWebResponse)req.GetResponse();

                return (new StreamReader(res.GetResponseStream()).ReadToEnd());
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

        //Post Request Methode
        public string PostRequest(string url, string refferer, string PostData)
        {
            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.CookieContainer = cookieJar;
                req.Method = "POST";
                req.KeepAlive = true;
                req.Referer = refferer;
                req.Timeout = (TimeOut);
                req.UserAgent = ("User-Agent: " + AssemblyInfo.AssemblyTitle + "/" + AssemblyInfo.AssemblyVersion);
                req.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding = new UTF8Encoding();
                byte[] PostDataBytes = encoding.GetBytes(PostData);
                req.ContentLength = PostDataBytes.Length;
                Stream stream = req.GetRequestStream();
                stream.Write(PostDataBytes, 0, PostDataBytes.Length);
                stream.Close();

                res = (HttpWebResponse)req.GetResponse();

                return (new StreamReader(res.GetResponseStream()).ReadToEnd());
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
    }
}
